<?php


namespace app\xcxapi\service;

use app\common\service\BaseService;
use app\lib\exception\BaseException;
use app\models\CampusModel;
use app\models\CourseModel;
use app\models\ClassRoomModel;
use app\models\StudentModel;
use app\models\GradesDetailsListsModel;
use app\models\GradesDetailsModel;
use app\models\StudentSubjectClassModel;
use app\models\StudentSubjectInfosClassModel;

class RemedialService extends BaseService
{
    /**
     * User: chenben
     * Date: 2020/02/19.
     *
     * @param $params
     *
     * @return array
     */
    public function remedialLists($params)
    {
        try {
        $where = ['attendance' => 0,'status' => 1, 'lessons_status' => 0]; //未考勤,已上课,未补课

        if (isset($params['student_name']) && '' !== $params['student_name']) {
            $where['student_name'] = ['like', '%'.$params['student_name'].'%'];
        }


        //获取补课学生
        if(xcxapi_get_current_wtype() == 5){
            if(xcxapi_get_current_group_type() == 2){  //老师类
                $grades_res = (new GradesDetailsModel())->where(['user_teacher_id' => xcxapi_get_current_user_id()])->column('id');
                $grades_res_str = implode(',',$grades_res);
                $where['class_subject_id'] = ['in',$grades_res_str];
            }else if(xcxapi_get_current_group_type() == 3){  //助教类
                $grades_res = (new GradesDetailsModel())->where(['user_assistant_id' => xcxapi_get_current_user_id()])->column('id');
                $grades_res_str = implode(',',$grades_res);
                $where['class_subject_id'] = ['in',$grades_res_str];
            }else if(xcxapi_get_current_group_type() == 4){ //班主任
                $grades_res = (new GradesDetailsModel())->where(['user_master_id' => xcxapi_get_current_user_id()])->column('id');
                $grades_res_str = implode(',',$grades_res);
                $where['class_subject_id'] = ['in',$grades_res_str];
            }else if(xcxapi_get_current_group_type() == 5){ //教务类
                $grades_res = (new GradesDetailsModel())->where(['user_edu_id' => xcxapi_get_current_user_id()])->column('id');
                $grades_res_str = implode(',',$grades_res);
                $where['class_subject_id'] = ['in',$grades_res_str];
            }
        }
		
		 $this->data = (new StudentSubjectInfosClassModel())
                ->where($where)
                ->order('id desc')
                ->select()
                ->toArray();
				
		foreach ($this->data as &$datum) {
                $student_res = (new StudentModel())->get(['id' => $datum['student_id']]);
				$datum['student_name'] = $student_res['student_name'];
				$datum['student_phone'] = $student_res['phone'];
				$datum['student_number'] = $student_res['student_number'];
				$datum['course_name'] = (new CourseModel())->get(['id' => $datum['course_id']])['course_name'];
				$datum['campus_name'] = (new CampusModel())->get(['id' => $datum['campus_id']])['campus_name'];
				$datum['grades_name'] = (new GradesDetailsModel())->get(['id' => $datum['class_subject_id']])['grades_name'];
            }
		
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }

    /**
     * User: chenben
     * Date: 2020/02/19.
     *
     * @param $params
     *
     * @return array
     */
    public function remedialFollowGrade($params)
    {
        try {
            $ids = $params['ids']; //补课列表id，用逗号连接
            $ids_arr = explode(',', $ids); //分割成数组
            $id = $params['id']; //所跟课节id
            $params['campus_id'] = 1;
            //			$params['campus_id'] = xcxapi_get_current_campus_id();
            $course_where = [];
            $course_where['campus_id'] = $params['campus_id'];
            $result = (new StudentSubjectInfosClassModel())->where($course_where)->select();
            $result_gradeslist = (new GradesDetailsListsModel())->get(['id' => $id]);  //班级id

            $save_student_data = [];  //学生表
            $save_infos_data = []; //学生上课详情表

            foreach ($result as $key => $value) {
                if (\in_array($value['id'], $ids_arr, true)) {   //包含在数组内
                    //edu_class_subject_student
                    $item = [];
                    $item['class_subject_id'] = $result_gradeslist['class_manage_id'];
                    $item['student_id'] = $value['student_id'];
                    $item['student_name'] = $value['student_name'];
                    $item['student_type'] = 3;  //补课学生
                    $item['room_id'] = $result_gradeslist['class_room_id'];  //教室ID
                    $item['campus_id'] = $params['campus_id'];
                    $item['contract_number'] = $value['contract_number'];
                    $item['status'] = $value['report_status'];  //1:课程分配  2:班级分配  3:试听分配
                    $save_student_data[] = $item;

                    //edu_class_subject_student_infos
                    $info_item = [];
                    $info_item['class_manage_details_id'] = $id;
                    $info_item['class_subject_id'] = $result_gradeslist['class_manage_id'];
                    $info_item['student_id'] = $value['student_id'];
                    $info_item['student_name'] = $value['student_name'];
                    $info_item['room_name'] = $result_gradeslist['class_room'];
                    $info_item['weekday'] = $result_gradeslist['weekday'];
                    $info_item['class_date'] = $result_gradeslist['class_date'];
                    $info_item['course_id'] = $result_gradeslist['course_id'];
                    $info_item['contract_number'] = $value['contract_number'];
                    $info_item['room_id'] = $result_gradeslist['class_room_id'];
                    $info_item['attendance'] = $value['attendance'];  //考勤状态
                    $info_item['charging'] = $value['charging'];  //计费状态
                    $info_item['campus_id'] = $value['campus_id'];

                    $start = strtotime($result_gradeslist['class_subject_start']);  //开始时间
                    $end = strtotime($result_gradeslist['class_subject_end']);  //结束时间

                    $duration = ceil(($end - $start) / 60); //节课时长
                    $info_item['duration'] = $duration;

                    $info_item['eliminated_nums'] = $value['eliminated_nums'];
                    $info_item['surplus_class_elimination'] = $value['surplus_class_elimination'];
                    $info_item['surplus_class_elimination_give'] = $value['surplus_class_elimination_give'];
                    $info_item['report_status'] = $value['report_status'];
                    $info_item['give_status'] = $value['give_status'];
                    $info_item['amount_deducted'] = $value['amount_deducted'];
                    $info_item['status'] = 0;
                    $info_item['lessons_status'] = 0;
                    $info_item['lessons_id'] = $value['id'];
                    //操作人
                    $info_item['operatorer'] = get_current_name();  //操作人

                    $info_item['follow_status'] = 2; //跟班课节

                    $save_infos_data[] = $info_item;

                    //更新补课状态
                    if (!(new StudentSubjectInfosClassModel())->where(['id' => $value['id']])->update(['lessons_status' => 1])) {
                        throw new BaseException('UPDATE_STATUS_FAILED');
                    }
                }
            }

            if (count($save_student_data) > 0) {
                if (!(new StudentSubjectClassModel())->insertAll($save_student_data)) {
                    throw new BaseException('INSERT_STUDENT_INFORMATIOM_FAILED');
                }
            }
            if (count($save_infos_data) > 0) {
                if (!(new StudentSubjectInfosClassModel())->insertAll($save_infos_data)) {
                    throw new BaseException('INSERT_STUDENT_CLASS_FAILED');
                }
            }
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }

	 /**
     * User: chenben
     * Date: 2020/04/18.
     * 插入补课班级
     * @param $params
     *
     * @return array
     */
    public function remedialInsertStudentInfos($params)
    {
        try {
            $ids = $params['ids'];
            $grades_name = $params['grades_name'];//补课班级名称
            $campus_id = $params['campus_id']; //补课校区ID
            $ids_arr = explode(',',$ids); //分割成数组
            $lesson_status = [];
            for ($g = 0; $g < count($ids_arr); $g ++){
                $item = [];
                $item['id'] = $ids_arr[$g];
                $item['lessons_status'] = 1;
                $lesson_status[] = $item;
            }

            $info_result = (new StudentSubjectInfosClassModel())->where("id in ($ids)")->select();
            $result = (new GradesDetailsModel())->get(['grades_name' => $grades_name]); //获取补课班级的名称对应的信息
            $result_detail_list = (new GradesDetailsListsModel())->get(['class_manage_id' =>$result['id'] ]);  //班级节课ID

            //遍历选中的同学
            $student_save_date = [];  //edu_class_subject_student
            $info_save_class_date = []; //edu_class_subject_student_infos
            foreach ($info_result as $key => $value){
                    $item = [];
                    $item['class_subject_id'] = $result['id']; // 班课表ID
                    $item['student_id'] =  $value['student_id']; //学生ID
                    $item['student_name'] = $value['student_name']; //学生姓名
                    $item['campus_id'] = $campus_id;  //补课校区ID
                    $item['room_id']  = $result['room_id']; //教室id
                    $item['student_type'] = 3; //补课类型
                    $item['status'] = $value['report_status'];  //1:课程  2:班级  3:试听
                    $item['contract_number'] = $value['contract_number']; //合同号
                    $student_save_date[] = $item;


                    $cell = [];
                    $cell['contract_number'] = $value['contract_number'];  //订单编号ID，非自增ID
                    $cell['student_id'] = $value['student_id'];  //学生ID
                    $cell['student_name'] = $value['student_name']; //学生姓名
                    $cell['surplus_class_elimination'] = $value['surplus_class_elimination']; //剩余课时
                    $cell['surplus_class_elimination_give'] = $value['surplus_class_elimination_give']; //赠送剩余课时
                    $cell['charging'] = $value['charging'];  //计费
                    $cell['eliminated_nums'] = $value['eliminated_nums'];  //课消数量，默认为0
                    $cell['amount_deducted'] = $value['amount_deducted'];  //扣除金额
                    $cell['room_id'] = $result['room_id'];;//教室ID
                    $cell['class_subject_id'] = $result['id'];//班级ID
                    $cell['class_manage_details_id'] = $result_detail_list['id']; //ID
                    $cell['room_name'] = $result['room_text']; //教室名称
                    $cell['report_status'] = $value['report_status'];  //1:课程  2:班级  3:试听
                    $cell['campus_id'] = $campus_id;  //补课校区ID
                     //操作人
                    $cell['operatorer'] = get_current_name();  //操作人

                    $cell['class_date'] = $result['class_start_date']; //开班日期
                    $cell['course_id'] = $result['course_id']; //课程ID

                    $start = strtotime($result_detail_list['class_subject_start']);  //开始时间
                    $end = strtotime($result_detail_list['class_subject_end']);  //结束时间
                    $cell['duration'] = ceil(($end - $start)/60);//上课时长

                    $cell['lessons_id'] = $value['id'];  //补课对象的自增ID
                    $cell['weekday'] = $result_detail_list['weekday']; //星期

                    $cell['follow_status'] = 1; //新开班课节

                    $info_save_class_date[] = $cell;
            }



            if(count($student_save_date) > 0) {
                if (!(new StudentSubjectClassModel())->insertAll($student_save_date)) {
					throw new BaseException('LESSON_DIVISION_FAILED');
                }

            }


            if(count($info_save_class_date) > 0){
                if (!(new StudentSubjectInfosClassModel())->insertAll($info_save_class_date)) {
					throw new BaseException('LESSON_INFO_CLASS_FAILED');
                }
            }

            //修改开班状态
            $result_ = (new StudentSubjectClassModel())->where(['class_subject_id' => $result['id']])->select();
            if(count($result_) > 0){
                if(!(new GradesDetailsModel())->update(['status' => 1],['id' => $result['id']])){
				throw new BaseException('UPDATE_LESSON_GRADES_OPEN_RECORD_FAILED');
                }

            }else{
                if(!(new GradesDetailsModel())->update(['status' => 0],['id' => $result['id']])){
				throw new BaseException('UPDATE_LESSON_GRADES_OPEN_RECORD_FAILED');
                }
            }

            if(!(new GradesDetailsModel())->update(['class_status' => 1],['id' => $result['id']])){
          		throw new BaseException('UPDATE_LESSON_GRADES_OPEN_STATUS_FAILED');
            }
            if(!(new StudentSubjectInfosClassModel())->saveAll($lesson_status)){
				throw new BaseException('UPDATE_LESSON_GRADES_OPEN_COURSE_STATUS_FAILED');
            }

        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }

    /**
     * User: chenben
     * Date: 2020/02/19.
     *
     * @param $params
     *
     * @return array
     */
    public function remedialDel($params)
    {
        try {
            $ids = $params['ids']; //补课列表id，用逗号连接
            (new StudentSubjectInfosClassModel())->where("id in (${ids})")->delete();
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }

	/**
	 * User: chenben
	 * Date: 2020/04/20
	 *
	 * @param $params
	 * @return array
	 */
    public function remedialFollowClass($params)
    {
        try {
		$arr = explode(',',$params['class_subject_id']);
        $arr = array_unique($arr);
        $str = implode(',',$arr);
        $where['class_manage_id'] = array('not in',$str);
		$where['graduation_status'] = 0; //未结业
		$where['campus_id'] = $params['campus_id'];
		$where['status'] = $params['status'];
		$where['course_id'] = $params['course_id'];
			
        ////获取教室课表
        if(xcxapi_get_current_wtype() == 5){
            if(xcxapi_get_current_group_type() == 2){  //老师类
                $grades_res = (new GradesDetailsModel())->where(['user_teacher_id' => xcxapi_get_current_user_id()])->column('id');
                $grades_res_str = implode(',',$grades_res);
                $where['class_subject_id'] = ['in',$grades_res_str];
            }else if(xcxapi_get_current_group_type() == 3){  //助教类
                $grades_res = (new GradesDetailsModel())->where(['user_assistant_id' => xcxapi_get_current_user_id()])->column('id');
                $grades_res_str = implode(',',$grades_res);
                $where['class_subject_id'] = ['in',$grades_res_str];
            }else if(xcxapi_get_current_group_type() == 4){ //班主任
                $grades_res = (new GradesDetailsModel())->where(['user_master_id' => xcxapi_get_current_user_id()])->column('id');
                $grades_res_str = implode(',',$grades_res);
                $where['class_subject_id'] = ['in',$grades_res_str];
            }else if(xcxapi_get_current_group_type() == 5){ //教务类
                $grades_res = (new GradesDetailsModel())->where(['user_edu_id' => xcxapi_get_current_user_id()])->column('id');
                $grades_res_str = implode(',',$grades_res);
                $where['class_subject_id'] = ['in',$grades_res_str];
            }
        }
		
		$this->data = (new GradesDetailsListsModel())
                ->where($where)
                ->order('id desc')
                ->select()
                ->toArray();
			
		foreach ($this->data as &$datum) {
				$datum['course_name'] = (new CourseModel())->get(['id' => $datum['course_id']])['course_name'];
				$res_grades = (new GradesDetailsModel())->get(['id' => $datum['class_manage_id']]);
				if($res_grades['preoccupation'] == 0){
					$datum['preoccupation'] = '不限';
				}else{
					$datum['preoccupation'] = $res_grades['preoccupation'];
				}
				$arrs = (new StudentSubjectClassModel())->where('class_subject_id', $datum['class_manage_id'])->column('student_id');
                //已报
                $datum['already_reported_num'] = count(array_unique($arrs));
				$datum['class_status'] = $res_grades['class_status'];
            }  
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }

	/**
	 * 加入补课课节
	 * User: chenben
	 * Date: 2020/04/20
	 *
	 * @param $params
	 * @return array
	 */
    public function remedialLessonClass($params)
    {
        try {
			
			$ids = $params['ids']; //补课列表id，用逗号连接
            $ids_arr = explode(',',$ids); //分割成数组
            $id = $params['id']; //所跟课节id
			$course_where = [];
			$course_where['campus_id'] = $params['campus_id'];
            $result = (new StudentSubjectInfosClassModel())->where($course_where)->select();
            $result_gradeslist = (new GradesDetailsListsModel())->get(['id' => $id]);  //班级id

            $save_student_data = [];  //学生表
            $save_infos_data = []; //学生上课详情表

            foreach ($result as $key => $value){
                if(in_array($value['id'],$ids_arr)){   //包含在数组内
                    //edu_class_subject_student
                    $item = [];
                    $item['class_subject_id'] = $result_gradeslist['class_manage_id'];
                    $item['student_id'] = $value['student_id'];
                    $item['student_name'] = $value['student_name'];
                    $item['student_type'] = 3;  //补课学生
                    $item['room_id'] = $result_gradeslist['class_room_id'];  //教室ID
                    $item['campus_id'] = $params['campus_id'];
                    $item['contract_number'] = $value['contract_number'];
                    $item['status'] = $value['report_status'];  //1:课程分配  2:班级分配  3:试听分配
                    $save_student_data[] = $item;

                    //edu_class_subject_student_infos
                    $info_item = [];
                    $info_item['class_manage_details_id'] = $id;
                    $info_item['class_subject_id'] = $result_gradeslist['class_manage_id'];
                    $info_item['student_id'] = $value['student_id'];
                    $info_item['student_name'] = $value['student_name'];
                    $info_item['room_name'] = $result_gradeslist['class_room'];
                    $info_item['weekday'] = $result_gradeslist['weekday'];
                    $info_item['class_date'] = $result_gradeslist['class_date'];
                    $info_item['course_id'] = $result_gradeslist['course_id'];
                    $info_item['contract_number'] = $value['contract_number'];
                    $info_item['room_id'] = $result_gradeslist['class_room_id'];
                    $info_item['attendance'] = $value['attendance'];  //考勤状态
                    $info_item['charging'] = $value['charging'];  //计费状态
                    $info_item['campus_id'] = $value['campus_id'];

                    $start = strtotime($result_gradeslist['class_subject_start']);  //开始时间
                    $end = strtotime($result_gradeslist['class_subject_end']);  //结束时间

                    $duration = ceil(($end - $start)/60); //节课时长
                    $info_item['duration'] = $duration;

                    $info_item['eliminated_nums'] = $value['eliminated_nums'];
                    $info_item['surplus_class_elimination'] = $value['surplus_class_elimination'];
                    $info_item['surplus_class_elimination_give'] = $value['surplus_class_elimination_give'];
                    $info_item['report_status'] = $value['report_status'];
                    $info_item['give_status'] = $value['give_status'];
                    $info_item['amount_deducted'] = $value['amount_deducted'];
                    $info_item['status'] = 0;
                    $info_item['lessons_status'] = 0;
                    $info_item['lessons_id'] = $value['id'];
                    //操作人
                    $info_item['operatorer'] = get_current_name();  //操作人

                    $info_item['follow_status'] = 2; //跟班课节

                    $save_infos_data[] = $info_item;

                    //更新补课状态
                    if(!(new StudentSubjectInfosClassModel())->where(['id' => $value['id']])->update(['lessons_status' => 1])){
                         throw new BaseException('UPDATE_STATUS_FAILED');
                    }

                }
            }

            if(count($save_student_data) > 0){
                if(!(new StudentSubjectClassModel())->insertAll($save_student_data)){
					throw new BaseException('INSERT_STUDENT_INFORMATIOM_FAILED');
                }
            }

            if(count($save_infos_data) > 0){
                if(!(new StudentSubjectInfosClassModel())->insertAll($save_infos_data)){
					throw new BaseException('INSERT_STUDENT_CLASS_FAILED');
                }
            }

           
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }
}
